import _ from 'lodash-es'
import axios from "axios"
import { message } from 'antd';
import type { AxiosInstance, AxiosRequestConfig, InternalAxiosRequestConfig, AxiosResponse } from 'axios'
// import { getLocalStorage } from '@/utils';

const baseURL = '/';
const timeout = 20000

type CustomResult<T> = {
  msg: string,
  status: number,
  data: T
}

type CustomResponse<T> = Promise<CustomResult<T>>

export class Request {
  instance: AxiosInstance
  baseConfig: AxiosRequestConfig = { baseURL, timeout }
  constructor(config: AxiosRequestConfig) {
    this.instance = axios.create(Object.assign(this.baseConfig, config));
    this.initInterceptor(this.instance);
  }

  initInterceptor(instance: AxiosInstance) {
    // 请求拦截器
    instance.interceptors.request.use(
      this.handleRequestInterceptor,
      (err: any) => {
        return Promise.reject(err)
      }
    );
    
    // 响应拦截器
    instance.interceptors.response.use(
      this.handleResponseSuccess,
      this.handleResponseError
    )
  }

  handleRequestInterceptor(config: InternalAxiosRequestConfig<any>) {
    // do something...
    // const token = getLocalStorage('Authorization')
    // console.log('interceptor ', token);
    // config.headers["Authorization"] = token
    console.log('config ', config);
    
    return config
  }

  handleResponseSuccess(resp: AxiosResponse<any, any>) {
    
    if (_.has(resp.data, 'status')) {
      const status = _.get(resp, 'data.status');
      const error = _.get(resp, 'data.msg', '请求错误!');
      if (status === 1) {
        message.error(error);
      }
    }
    console.log('resp ', resp.data);
    return resp.data
  }

  handleResponseError(err: any) {
    const errStatus = _.get(err, 'response.status');
    let errMessage = '';

    switch(errStatus) {
      case 400:
        errMessage = '请求错误(400)!';
        break
      case 401:
        errMessage = '未授权，请重新登陆';
        break
      default:
        break
    }

    message.error(errMessage);
    return Promise.reject(err);
  }

  request(config: AxiosRequestConfig) {
    return this.instance(config)
  }

  public get<T = any>(url: string, config?: AxiosRequestConfig): CustomResponse<T> {
    return this.instance.get(url, config)
  }

  public post<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): CustomResponse<T> {
    return this.instance.post(url, data, config)
  }

  public put<T = any>(
    url: string,
    data?: any,
    config?: AxiosRequestConfig
  ): CustomResponse<T> {
    return this.instance.put(url, data, config);
  }

  public delete<T = any>(
    url: string,
    config?: AxiosRequestConfig
  ): CustomResponse<T> {
    return this.instance.delete(url, config);
  }
}

export default new Request({})